package com.cbtx.module_sp

import android.app.Activity
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.WindowManager
import android.widget.Toast
import androidx.multidex.MultiDex
import com.cbtx.module.base.ContextManager
import com.cbtx.module.common.dialog.CommentConfirmDialog
import com.cbtx.module_sp.ui.activity.base.MyBaseVMActivity
import com.cbtx.module_sp.utils.NetWorkUtil
import com.txcb.lib.base.AppManager
import com.txcb.lib.base.utils.DeviceUtil
import com.txcb.lib.base.utils.FileUtils
import com.txcb.lib.base.utils.SharedPreferencesUtils
import com.txcb.lib.base.utils.ToastUtil
import java.io.File
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class MyApplication: Application() {

    companion object{
        var mAndroidId = ""
        var rebootTime: Long = System.currentTimeMillis()
        lateinit var instance: MyApplication
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        ignoreSSLHandshake()

        ContextManager.setContext(this)

        setActivityLifeCycle()
        FileUtils.ROOT_DIR = "txcb_tablet_sp"
        FileUtils.init(this)
//        FileUtils.getCacheDir()
        val basePath: String = FileUtils.getExternalStoragePath()
        val file = File(basePath)
        if (!file.exists()) {
            file.mkdirs()
        }

        FileUtils.getDownloadDir()

        mAndroidId = DeviceUtil.getSerialNumber(this)

        ToastUtil.init(this)
        SharedPreferencesUtils.initSharedPreferences(this)
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
//        registerReceiver(netBroadcastReceiver, intentFilter)

    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    private fun setActivityLifeCycle(){
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
                AppManager.getInstance().addActivity(activity)
            }
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {
                AppManager.getInstance().removeActivity(activity)
            }
        })


    }


    var netBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = connectivityManager.activeNetworkInfo
            if (networkInfo != null && networkInfo.isAvailable) {
                Toast.makeText(context,"网络已连接",Toast.LENGTH_SHORT).show();
                showNoNet(false)
//                reGetMainData()
            } else {
                Toast.makeText(context,"网络断开",Toast.LENGTH_SHORT).show();
                showNoNet(true)
            }
        }
    }


    var commentConfirmDialog: CommentConfirmDialog? = null

    fun showNoNet(isShow: Boolean) {


        if (!isShow) {
            if (commentConfirmDialog != null && commentConfirmDialog!!.isShowing) {
                commentConfirmDialog!!.dismiss()
                commentConfirmDialog = null
            }
            return
        }

        if (commentConfirmDialog != null && commentConfirmDialog!!.isShowing) {
            return
        }


        val lastActivity = AppManager.getInstance().currentActivity()

        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:$packageName")
            )
            lastActivity.startActivityForResult(intent, MyBaseVMActivity.REQUEST_OVERLAY)

            return
        }

        commentConfirmDialog = CommentConfirmDialog(lastActivity!!)

        //只有这样才能弹框
        if (Build.VERSION.SDK_INT >= 26) { //8.0新特性
            commentConfirmDialog!!.window!!.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
        } else {
            commentConfirmDialog!!.window!!.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        }
        commentConfirmDialog!!
            .setContent("哎呀，暂无网络，请前往设置")
            .setAgree("前往设置")
            .setOnDialogListener(object : CommentConfirmDialog.OnDialogListener {
                override fun onCancel() {
//                        commentConfirmDialog.dismiss();
                }

                override fun onAgree() {
                    commentConfirmDialog!!.dismiss()
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        val panelIntent =
                            Intent(Settings.Panel.ACTION_WIFI)
                        lastActivity?.startActivityForResult(
                            panelIntent,
                            MyBaseVMActivity.RQ_WIFI_SET
                        )
                    } else {
                        val intent = Intent()
                        intent.action = "android.net.wifi.PICK_WIFI_NETWORK"
                        intent.putExtra(":settings:show_fragment_as_subsetting", true)
                        lastActivity?.startActivityForResult(intent, MyBaseVMActivity.RQ_WIFI_SET)
                    }
                }
            })
        commentConfirmDialog!!.show()
    }

    fun getHeaderMap(): MutableMap<String, String> {
        var map = mutableMapOf<String, String>()
        var iMachine = MachineFactory.getAutoCreate(this)
        map["uniquedevicecode"] = iMachine.uniqueDeviceCode
        map["appversion"] = versionCode(this)!!
        map["appversioncode"] = versionName(this)!!
        map["firmwareversion"] = iMachine.frameworkVersion
        map["devicemodel"] = iMachine.model
        map["screenType"] = "INTERACTIVE"
        map["manualReg"] = "true"
        map["mac"] = iMachine.localMac
        map["producttype"] = iMachine.productType
        try {
            map["serial"] = if (TextUtils.isEmpty(Build.getSerial())) "" else Build.getSerial()
        } catch (e: Exception) {
            map["serial"] = ""
        }
        map["networkingWay"] = java.lang.String.valueOf(NetWorkUtil.getNetWorkState(this))
        return map
    }

    private fun versionCode(context: Context): String {
        val manager = context.packageManager
        var code :String = ""
        try {
            val info = manager.getPackageInfo(context.packageName, 0)
            code = info.versionCode.toString()
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return code
    }


    fun versionName(context: Context): String {
        val manager = context.packageManager
        var name = ""
        try {
            val info = manager.getPackageInfo(context.packageName, 0)
            name = info.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        var listStr = name.split(".")
        var result = ""
        listStr.forEach {
            result += it
        }
        return result
    }

    fun ignoreSSLHandshake() {
        try {
            val trustAllCerts =
                arrayOf<TrustManager>(object : X509TrustManager {
                    override fun getAcceptedIssuers(): Array<X509Certificate?>? {
                        return arrayOfNulls(0)
                    }

                    override fun checkClientTrusted(
                        certs: Array<X509Certificate?>?,
                        authType: String?
                    ) {
                    }

                    override fun checkServerTrusted(
                        certs: Array<X509Certificate?>?,
                        authType: String?
                    ) {
                    }
                })
            val sc = SSLContext.getInstance("TLS")
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.socketFactory)
            HttpsURLConnection.setDefaultHostnameVerifier { hostname, session -> true }
        } catch (e: java.lang.Exception) {
        }
    }

}